go to previous page   go to home page   go to next page

Answer:

When the entries of a dictionary are put in order, does the order depend on the definition? No.

Should the compareTo() method depend on the definition? No.

Fill in the blank to complete the compareTo() method.

  public int compareTo( Entry other )
  {
   return getWord().compareTo( other.getWord() );
  }

Another solution is:

  public int compareTo( Entry other )
  {
   return word.compareTo( other.word );
  }

Entry Testing Program

Here is a program that tests that the Entry class works as expected.

import java.util.Arrays;

class Entry implements Comparable<Entry>
{
  .  .  .
}

class EntryTester
{
  
  public static void main ( String[] args )
  {
    Entry[] wordList = new Entry[10];
    
    wordList[0] = new Entry( "WWW", "World Wide Web" );
    wordList[1] = new Entry( "HTTP","Hypertext Transport Protocol" );
    wordList[2] = new Entry( "DNS", "Domain Name System" );
    wordList[3] = new Entry( "AWT", "Application Windowing Toolkit" );
    wordList[4] = new Entry( "CPU", "Central Processing Unit" );
    wordList[5] = new Entry( "RAM", "Random Access Memory" );
    wordList[6] = new Entry( "URL", "Uniform Resource Locator" );
    wordList[7] = new Entry( "GUI", "Graphical User Interface" );
    wordList[8] = new Entry( "API", "Application Programming Interface" );
    wordList[9] = new Entry( "ROM", "Read-only Memory" );
    
    Arrays.sort( wordList );
    
    for ( int j=0; j<wordList.length; j++ )
      System.out.println( wordList[j].toString() );
  }  

}

The program outputs:

API     Application Programming Interface
AWT     Application Windowing Toolkit
CPU     Central Processing Unit
DNS     Domain Name System
GUI     Graphical User Interface
HTTP    Hypertext Transport Protocol
RAM     Random Access Memory
ROM     Read-only Memory
URL     Uniform Resource Locator
WWW     World Wide Web

The sort() method used our compareTo() to determine the order of the entries.


QUESTION 17:

Must an array be in sorted order for it to be searched?